package com.example.estest.elasticsearchconfig;
import com.example.estest.util.DateUtil;
import com.example.estest.util.FileUtils;
import com.example.estest.util.IpUtil;
import com.example.estest.util.LogParser;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class LogstashEquivalent {

    private static final String INDEX_NAME = "log_data_mail_login"; // 替换为你实际的Elasticsearch索引名称

    public static final Object lockerEsRequest = new Object();


    //public static final String logmessage = "2023-11-13 15:42:31 [24315]:auth_type:[pop],extra_type:[],acct_id:[498483],domain_id:[496704],acct_type:[0],domain_type:[0].acct_name:[yuanren],real_acc_name:[yuanren],domain_name:[sgcc.com.cn].real_domain_name:[sgcc.com.cn],admin_type:[0],client_ip:[122.10.141.107],server_name:[localhost],reasult:[Auth Success]";


    public  void logstash(String logmessage,String targetFilePath,
                          String logpath,RestHighLevelClient client,
                          String finishlog) {

        // 示例数据

        LinkedHashMap<String, Object> logData = new LinkedHashMap<>();
        LogParser.func(logData,logmessage,logpath);
        String clientIP = logData.get("clientIP").toString();
        LinkedHashMap<String, Object> stringStringConcurrentHashMap;
        String regex = "^(127\\.0\\.0\\.1)|(localhost)|(^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(172\\.((1[6-9])|(2\\d)|(3[01]))\\.\\d{1,3}\\.\\d{1,3})|(192\\.168\\.\\d{1,3}\\.\\d{1,3})$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(clientIP);
        if (!matcher.find()) {
            // 匹配，执行 GeoIP 相关逻辑
            stringStringConcurrentHashMap = IpUtil.ipUtil(clientIP);
        } else {
            // 不匹配，执行内网逻辑
            stringStringConcurrentHashMap = IpUtil.NotIsIpUtil(clientIP);
        }
        logData.remove("clientIP");
        logData.put("sip",stringStringConcurrentHashMap);
        Object result = logData.get("result");
        if(result.toString().contains("Success") || result.toString().contains("成功")) {
            logData.put("result","login Success");
        } else {
            logData.put("result","login Fail");
        }
        logData.put("mail_name",logData.get("acctNames"));
        logData.put("path",targetFilePath);
        logData.put("type","log-zsy-auth");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format;
        format = simpleDateFormat.format(new Date());
        logData.put("插入时间",format+" "+System.currentTimeMillis());


//        // 发送数据到Elasticsearch
        sendToElasticsearch(logData,logpath,client);
        FileUtils.writeStringadd(finishlog, DateUtil.getData()+"------"+"清洗完成一条数据 "+logData);

    }

    /*
    上传到es
     */
    private  void sendToElasticsearch(Map<String, Object> logData,String logpath,
                                      RestHighLevelClient client) {


//        try (RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(new HttpHost(ELASTICSEARCH_HOST, ELASTICSEARCH_PORT, "http"))
//                        .setHttpClientConfigCallback(httpClientBuilder -> {
//                            // 提供用户名和密码
//                            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//                            credentialsProvider.setCredentials(AuthScope.ANY,
//                                    new UsernamePasswordCredentials("elastic","elastic"));
//                            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
//                            return httpClientBuilder;
//                        })
//        )) {
//            // 准备IndexRequest
//            IndexRequest indexRequest = new IndexRequest(INDEX_NAME)
//                    .source(logData);
//
//            // 发送IndexRequest到Elasticsearch
//            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
//
//            // 处理响应
//            String documentId = response.getId();
//            System.out.println("Data sent successfully to Elasticsearch. Document ID: " + documentId);
//        } catch (IOException e) {
//            e.printStackTrace();
//            FileUtils.writeStringadd(logpath+"\\"+"error.log",e.toString());
//            System.out.println("连接失败");
//        }

        IndexRequest indexRequest = new IndexRequest(INDEX_NAME)
                .source(logData)
                .timeout(TimeValue.timeValueSeconds(30));
        try {
            synchronized (lockerEsRequest) {
                IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
                String documentId = response.getId();
                System.out.println(response.status().getStatus());
                System.out.println(response.getResult());
                System.out.println("Data sent successfully to Elasticsearch. Document ID: " + documentId);
            }
        }catch (Exception e) {
            FileUtils.writeStringadd(logpath+"\\"+"error.log", DateUtil.getData()+"------"+e+logData+"入库失败");
            throw new RuntimeException(e);
        }
    }
}
